package com.itc.dispatch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.CommonUtils;
import com.itc.common.core.utils.LocalDateTimeUtils;
import com.itc.common.core.utils.OkHttpUtil;
import com.itc.common.core.utils.StringUtils;
import com.itc.common.security.utils.SecurityUtils;
import com.itc.dispatch.domain.SysSms;
import com.itc.dispatch.domain.dto.SysSmsPageDto;
import com.itc.dispatch.service.SysSmsService;
import com.itc.dispatch.mapper.SysSmsMapper;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
* @author 91516
* @description 针对表【sys_sms】的数据库操作Service实现
* @createDate 2024-09-24 13:39:47
*/
@Service
public class SysSmsServiceImpl extends ServiceImpl<SysSmsMapper, SysSms>
    implements SysSmsService{

    private static String APP_ID = "EUCP-EMY-SMS1-3KC9K";
    private static String SECRET_KEY = "EUCP-EMY-SMS1-3KC9K";

    @Override
    public R smsSend(SysSms sysSms) {
        Map<String, String> headers = new HashedMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

//        String timestamp = LocalDateTimeUtils.getCurrentLocalDateTime("yyyyMMddHHmmss");
//        String sign = getMD5Hash(APP_ID+SECRET_KEY+timestamp);

        //暂时写死
        String timestamp = "20201123101000";
        String sign = "41C38C880035F349A9FDD07B7502846A";

        String phone = sysSms.getPhone();
        String content = "";
        try {
            content = CommonUtils.encodeChineseInUrl(sysSms.getSmsContent());
        }catch (Exception e){
            System.out.println("中文路径替换异常："+e.getMessage());
            e.printStackTrace();
        }

        //记录短信日志
        sysSms.setCreatedBy(SecurityUtils.getUsername());
        sysSms.setCreatedDate(LocalDateTimeUtils.getCurrentLocalDateTime());

        Object resultObj = OkHttpUtil.sendOkHttpClient("http://10.81.180.66:45610/simpleinter/sendSMS?appId="+APP_ID+"&timestamp="+timestamp+"&sign="+sign+"&mobiles="+phone+"&content="+content
                , "GET",null,headers);
        if(resultObj == null){
            sysSms.setStatus("0");
            this.save(sysSms);
            return R.fail("短信发送失败");
        }
        JSONObject dataJson = JSONObject.parseObject(resultObj.toString());
        if(!StringUtils.equals("SUCCESS",dataJson.getString("code"))){
            sysSms.setStatus("0");
            sysSms.setErrorMsg(dataJson.toString());
            this.save(sysSms);
            return R.fail("短信发送失败");
        }
        sysSms.setStatus("1");
        this.save(sysSms);
        return R.ok();
    }

    @Override
    public R getPage(Page page, SysSmsPageDto pageDto) {
        Page<SysSms> resultPage = this.baseMapper.selectPage(page,
                new LambdaQueryWrapper<SysSms>()
                .like(StringUtils.isNotBlank(pageDto.getPhone()),SysSms::getPhone,pageDto.getPhone())
                .like(StringUtils.isNotBlank(pageDto.getSmsContent()),SysSms::getSmsContent,pageDto.getSmsContent())
                .eq(StringUtils.isNotBlank(pageDto.getCreatedBy()),SysSms::getCreatedBy,pageDto.getCreatedBy())
                .eq(StringUtils.isNotBlank(pageDto.getSysType()),SysSms::getSysType,pageDto.getSysType())
                .like(StringUtils.isNotBlank(pageDto.getProcessName()),SysSms::getProcessName,pageDto.getProcessName())
                .orderByDesc(SysSms::getCreatedDate)
        );
        return R.ok(resultPage);
    }

    public static String getMD5Hash(String input) {
        try {
            // 创建一个MessageDigest实例，指定MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 对输入字符串进行摘要计算
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            // 将字节数组转换为十六进制字符串
            BigInteger bigInt = new BigInteger(1, digest);
            String hashText = bigInt.toString(16);
            // 补全32位长度
            while (hashText.length() < 32) {
                hashText = "0" + hashText;
            }
            return hashText;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}




